﻿using System;
using System.Globalization;
using System.IO;
using Avalonia.Data.Converters;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
using TagLib;
using File = System.IO.File;

namespace MusicDiary.App.Converters;

public class ImageConverter : IValueConverter
{
    public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        if (value is string s)
            return new Bitmap(GetImage(s));
        if (value is byte[] a)
            return new Bitmap(new MemoryStream(a));
        return value;
    }

    public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        return value;
    }
    
    private Stream GetImage(string url)
    {
        if (!File.Exists(url))
            return Default();
        TagLib.File currentFile = TagLib.File.Create(url);
        IPicture[] pictures = currentFile.Tag.Pictures;
        if (pictures.Length <= 0)
            return Default();
        IPicture picture = pictures[0];
        return new MemoryStream(picture.Data.Data);
    }

    private Stream Default() => AssetLoader.Open(new Uri("Default.png"));
}